<?php
namespace app\common\model;

use hema\wechat\Driver;

/**
 * 小程序模型
 */
class Applet extends BaseModel
{
    //定义表名
    protected $name = 'applet';

    // 定义主键
    protected $pk = 'applet_id';

    // 追加字段
    protected $append = [];

    /**
     * 关联模板表
     */
    public function template()
    {
        return $this->belongsTo('app\\common\\model\\Template','app_type','app_type');
    }

    /**
     * 关联分账账户表 - 仅代理
     */
    public function divide()
    {
        return $this->belongsTo('app\\common\\model\\DivideAccount','applet_id','applet_id');
    }
	
    /**
     * 微信头像
     */
    public function getHeadImgAttr($value)
    {
        empty($value) && $value = base_url() . 'assets/img/no_pic.jpg';
        return $value;
    }
	
	/**
     * 账号来源
     */
    public function getSourceAttr($value)
    {
        $status = [10 => '自注', 20 => '平台'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 是否授权
     */
    public function getStatusAttr($value)
    {
        $status = ['否','是'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 模板类型
     */
    public function getShopModeAttr($value)
    {
		$status = [10 => '单门店', 20 => '多门店'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 到期时间
     */
    public function getExpireTimeAttr($value)
    {
		$day = round(($value - time()) / 86400);
        return ['text' => date("Y-m-d", $value), 'value' => $value, 'day' => $day];
    }
	
	/**
     * 获取列表 
     *  $type 0全部 10已授权 20授权已到期
     */
    public function getList($type = 0, $user_id = 0, $agent_id = 0)
    {
        $with = ['template'];
		// 筛选条件
        $filter = [];
        $user_id > 0 && $filter['user_id'] = $user_id;
        if($agent_id > 0){
            $filter['agent_id'] = $agent_id;
            array_push($with,'divide');
        }
        if($type > 0){
        	$filter['status'] = 1;
        	$type == 20 && $filter['expire_time'] = ['<',time()];
        }
        // 执行查询
        return $this->with($with)
            ->where($filter)
            ->order('applet_id','desc')
            ->paginate(['list_rows'=>15,'query' => request()->param()]);
    }

    /**
     * 获取小程序信息 - 回调接口
     */
    public static function getApplet(array $filter = [])
    {
        return self::withoutGlobalScope()->where($filter)->find();
    }

    /**
     * 更新小程序设置
     * @param string $dataType 数据类型 app=用户更新,apply=新注册更新
     */
    public function edit(array $data, string $dataType = 'app')
    {
    	if($dataType == 'app'){
	        $wx = new Driver;
	        //添加服务器域名
	        if($this->api_domain != $data['api_domain']){
	            $result = $wx->setServeDomain($this->applet_id,$data['api_domain']);
	            if($result['errcode'] != 0){
	                $this->error = '服务器域名设置失败！code：'.$result['errcode'].',msg：'.$result['errmsg'];
	                return false;
	            }
	        }
	        if($this->signature != $data['signature']){
	            $result = $wx->setSignature($this->applet_id,$data['signature']);
	            if($result['errcode'] != 0){
	                $this->error = '简介设置失败！code：'.$result['errcode'].',msg：'.$result['errmsg'];
	                return false;
	            }
	        }
	        if($this->webview_domain != $data['webview_domain']){
	            if(!$wx->setWebDomain($this->applet_id,$data['webview_domain'])){
	                $this->error = $wx->getError();
	                return false;
	            }
	        }
        }
        return $this->save($data) !== false;
    }

    /**
     * 修改小程序密码
     */
    public function renew(array $data)
    {       
        if ($data['password'] != $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }
        $data['password'] = hema_hash($data['password']);
        return $this->save($data) !== false;
    }

	/**
     * 根据条件统计数量
     */
    public static function getCount($agent_id = 0)
    {
		$self = new static;
        $count = array();
        $filter = [];
        $agent_id > 0 && $filter['agent_id'] =  $agent_id;
		//全部统计
		$count['all'] = self::where($filter)->count();//全部数量
		//今天统计
		$star = strtotime(date('Y-m-d 00:00:00',time()));
		$count['today'] = self::where($filter)->where('create_time','>',$star)->count();//全部数量
		//昨天统计
		$star = strtotime("-1 day");
		$end = strtotime(date('Y-m-d 00:00:00',time()));
		$count['today2'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		//前天统计
		$star = strtotime("-2 day");
		$end = strtotime("-1 day");
		$count['today3'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		//-4天统计
		$star = strtotime("-3 day");
		$end = strtotime("-2 day");
		$count['today4'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		//-5天统计
		$star = strtotime("-4 day");
		$end = strtotime("-3 day");
		$count['today5'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		//-6天统计
		$star = strtotime("-5 day");
		$end = strtotime("-4 day");
		$count['today6'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		//-7天统计
		$star = strtotime("-6 day");
		$end = strtotime("-5 day");
		$count['today7'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		//本月统计 
		$end = mktime(0,0,0,date('m'),1,date('y')); 
		$count['month'] = self::where($filter)->where('create_time','>',$end)->count();//全部数量
		//上月统计  
		$star = mktime(0,0,0,date('m')-1,1,date('y'));
		$count['month2'] = self::where($filter)->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		return $count;
    }	
	
}
